import Main
import pandas as pd
import openpyxl
import xlrd
import shutil

def row2str(row_data):
    values = "";
    for i in range(len(row_data)):
        if i == len(row_data) - 1:
            values = values + str(row_data[i])
        else:
            values = values + str(row_data[i]) + ","
    return values

# 处理xlsx
def fun(filename):
    # 无后缀的文件名
    name = filename.split('.')[0]
    # 源文件
    src_file = Main.file_path + "/" + filename
    # 失败文件
    wrong = Main.result_path + "/wrong"
    # txt文件
    target = Main.result_path + "/txt" + '/' + name + '.txt'
    # 正常文件
    normal = Main.result_path + "/normal"
    # 失败日志
    log = Main.result_path + '/wrong.txt'

    try:
        wb = openpyxl.load_workbook(src_file)
        sheets = wb.sheetnames
        for sheet in sheets:
            # print(sheet)
            df = pd.read_excel(src_file, sheet_name=sheet, header=None)
            # print('开始写入txt文件...')
            # 保存txt文件
            df.to_csv(target, header=None, sep=',', index=False)
            # print('文件写入成功!')
    except BaseException as e:
        shutil.move(src_file, wrong + "/")
        with open(log, "a") as file:  # "a"代表追加内容
            file.write(filename + " " + repr(e) + "\n")
    else:
        shutil.move(src_file, normal + "/")


# 处理xls格式的数据
def fun2(filename):
    # 无后缀的文件名
    name = filename.split('.')[0]
    # 源文件
    # src_file = './' + filename
    src_file = Main.file_path + "/" + filename
    # 失败文件
    wrong = Main.result_path + "/wrong"
    # txt文件
    target = Main.result_path + "/txt" + '/' + name + '.txt'
    # 正常文件
    normal = Main.result_path + "/normal"
    # 失败日志
    log = Main.result_path + '/wrong.txt'

    try:
        data = xlrd.open_workbook(src_file)
        # 文件读写方式是追加
        file = open(target, "a")
        # 表头
        table = data.sheets()[0]
        # 行数
        row_cnt = table.nrows
        # 列数
        col_cnt = table.ncols
        # 第一行数据
        title = table.row_values(0)

        for j in range(1, row_cnt):
            row = table.row_values(j)
            # 调用函数，将行数据拼接成字符串
            row_values = row2str(row)
            # 将字符串写入新文件
            file.writelines(row_values + "\r")
        # 关闭写入的文件
        file.close()
    except BaseException as e:
        shutil.move(src_file, wrong + "/")
        with open(log, "a") as file:  # "a"代表追加内容
            file.write(filename + " " + repr(e) + "\n")
    else:
        shutil.move(src_file, normal + "/")


